import { _decorator, Component, EventTouch, Input, input, Node, UITransform, Vec2 } from 'cc'
const { ccclass } = _decorator

@ccclass('JoyStickManager')
export class JoyStickManager extends Component {
  // 摇杆外面那个有透明度的大圆
  private body: Node
  // 摇杆中间那个白色小圆
  private stick: Node
  // 摇杆默认位置
  private defaultPos: Vec2
  // 摇杆半径
  private radius: number

  input: Vec2 = Vec2.ZERO

  onLoad() {
    this.body = this.node.getChildByName('Body')
    this.stick = this.body.getChildByName('Stick')
    this.defaultPos = new Vec2(this.body.position.x, this.body.position.y)
    this.radius = this.body.getComponent(UITransform).contentSize.x / 2

    input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
    input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
    input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
  }

  onDestroy() {
    input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
    input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
    input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
  }

  onTouchStart(event: EventTouch) {
    const touchPos = event.getUILocation()
    this.body.setPosition(touchPos.x, touchPos.y)
  }

  onTouchMove(event: EventTouch) {
    const touchPos = event.getUILocation()
    // 摇杆跟随，限制在摇杆半径内
    const stickPos = new Vec2(touchPos.x - this.body.position.x, touchPos.y - this.body.position.y)
    if (stickPos.length() > this.radius) {
      stickPos.multiplyScalar(this.radius / stickPos.length())
    }

    this.stick.setPosition(stickPos.x, stickPos.y)

    this.input = stickPos.clone().normalize()
  }

  onTouchEnd() {
    this.body.setPosition(this.defaultPos.x, this.defaultPos.y)
    this.stick.setPosition(0, 0)
    this.input = Vec2.ZERO
  }
}
